package org.jw.wishlist.resolver;

import static com.google.common.base.Preconditions.checkState;
import static org.apache.commons.lang3.ObjectUtils.isNotEmpty;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Optional;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jw.wishlist.entity.source.ItemSource;
import org.springframework.web.client.RestTemplate;

/**
 * @author Jiawei Zhao
 */
@Slf4j
public class HaoHaoZhuSourceResolver extends ItemSourceSupports implements ItemSourceResolver {

  private static final String SOURCE_KEY = "haohaozhu";

  public HaoHaoZhuSourceResolver(RestTemplate restTemplate) {
    super(restTemplate);
  }

  @Override
  public ItemSource resolve(String linkCode) {

    String url = extractUrl(linkCode);
    String res = restTemplate.getForObject(url, String.class);
    checkState(isNotEmpty(res), "解析失败");

    Document document = Jsoup.parse(res);
    Info info = Optional.ofNullable(document.select("script[id='__NEXT_DATA__']").first())
        .map(Element::data)
        .map(this::readJson)
        .map(x -> x.get("props"))
        .map(x -> x.get("pageProps"))
        .map(x -> x.get("noteInfo"))
        .map(x -> x.get("photo_info"))
        .map(x -> OBJECT_MAPPER.convertValue(x, Info.class))
        .orElseThrow(() -> new IllegalStateException("解析失败"));

    return ItemSource.builder()
        .key(SOURCE_KEY)
        .itemId(info.getId())
        .name(info.getName())
        .linkCode(linkCode)
        .originUrl(url)
        .accessUrl(url)
        .pictureUrl(info.getPic())
        .build();
  }

  private JsonNode readJson(String jsonString) {
    try {
      return OBJECT_MAPPER.readTree(jsonString);
    } catch (JsonProcessingException e) {
      throw new IllegalStateException("解析失败");
    }
  }

  @Data
  public static class Info {

    private String id;

    @JsonProperty("title")
    private String name;

    @JsonProperty("new_pic_url")
    private String pic;

  }

}
